package com.leyou.cart.service;

import com.leyou.cart.interceptor.UserInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.pojo.UserInfo;
import com.leyou.common.utils.JsonUtils;
import com.netflix.discovery.converters.Auto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * lcd  2020/6/16
 * Description:
 */
@Service
public class CartService {
    private static final String KEY_PREFIX = "cart:user:id:";
    @Autowired
    private StringRedisTemplate redisTemplate;

    //购物车结构是一个双层Map:::::::Map<String,Map<String,String>>
    public void addCart(Cart cart) {
        UserInfo userInfo = UserInterceptor.get();
        String key = KEY_PREFIX + userInfo.getId();
        //第一层key就是用户id(附带购物车前缀)
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(key);
        //第二层key就是Cart对象的skuId,拿到最终的value(Cart对象的json字符串)
        String hashKey = cart.getSkuId().toString();
        if (operations.hasKey(hashKey)) {
            //原先有数据了,就取出来增加数量
            String jsonCart = operations.get(hashKey).toString();
            Cart cacheCart = JsonUtils.toBean(jsonCart, Cart.class);
            cacheCart.setNum(cacheCart.getNum() + cart.getNum());
            operations.put(hashKey, JsonUtils.toString(cacheCart));
        } else {
            //原先没有数据,就新增数据
            operations.put(hashKey, JsonUtils.toString(cart));
        }
    }

    public List<Cart> queryCartList() {
        UserInfo userInfo = UserInterceptor.get();
        String key = KEY_PREFIX + userInfo.getId();
        if (!redisTemplate.hasKey(key)) {
            throw new LyException(ExceptionEnum.CART_NOT_FOUND);
        }
        List<Object> carts = redisTemplate.opsForHash().values(key);
        return carts.stream().map(x -> JsonUtils.toBean(x.toString(), Cart.class)).collect(Collectors.toList());
    }

    public void updateCartNumber(Long skuId, Integer num) {
        UserInfo userInfo = UserInterceptor.get();
        String key = KEY_PREFIX + userInfo.getId();
        //第一层key就是用户id(附带购物车前缀)
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(key);
        //第二层
        String hashKey = skuId.toString();
        String jsonCart = operations.get(hashKey).toString();
        Cart cart = JsonUtils.toBean(jsonCart, Cart.class);
        cart.setNum(num);
        operations.put(hashKey, JsonUtils.toString(cart));

    }

    public void deleteCart(Long skuId) {
        UserInfo userInfo = UserInterceptor.get();
        String key = KEY_PREFIX + userInfo.getId();
        redisTemplate.opsForHash().delete(key, skuId.toString());
    }
}
